package com.ls.datasource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * 数据库源配置
 * @author lishuai
 *
 */
@Configuration
public class DataSourceConfiguration {

	private Logger log = LoggerFactory.getLogger(DataSourceConfiguration.class);
	
	private Class<? extends DataSource> dataSourceType = com.alibaba.druid.pool.DruidDataSource.class;
    
	/**
	 * 写库 数据源配置
	 * @return
	 */
	@Bean(name = "masterDataSource")
    @Primary
    @ConfigurationProperties(prefix = "mysql.datasource.master")
    public DataSource writeDataSource() {
        log.info("-------------------- masterDataSource init ---------------------");
        return DataSourceBuilder.create().type(dataSourceType).build();
    }
	
	/**
     * 从库配置
     * @return
     */
    @Bean(name = "slave1DataSource")
    @ConfigurationProperties(prefix = "mysql.datasource.slave1")
    public DataSource readDataSourceOne() {
        log.info("-------------------- slave1 DataSourceOne init ---------------------");
        return DataSourceBuilder.create().type(dataSourceType).build();
    }

    @Bean(name = "slave2DataSource")
    @ConfigurationProperties(prefix = "mysql.datasource.slave2")
    public DataSource readDataSourceTwo() {
        log.info("-------------------- slave2 DataSourceTwo init ---------------------");
        return DataSourceBuilder.create().type(dataSourceType).build();
    }

    public Class<? extends DataSource> getDataSourceType() {
        return dataSourceType;
    }

    public void setDataSourceType(Class<? extends DataSource> dataSourceType) {
        this.dataSourceType = dataSourceType;
    }
}
